package net.zjitc.list;

public class MyArrayList<E> implements MyList<E> {
    private Object[] arr=new Object[10];
    private  int size=0;
    @Override
    public boolean add(E date) {
       if (size>=arr.length){
           Object[] temp=new Object[size*2];
           for (int i = 0; i < arr.length; i++) {
               temp[i]=arr[i];
           }
           arr=temp;
       }
       arr[size++]=date;

        return true;
    }

    @Override
    public boolean add(int index, E date) {
        //索引不在范围
        if (size>index||index<0){
         throw  new RuntimeException("索引越界");
        }
        //空间不够
        if (size>=arr.length){
            Object[] temp=new Object[size*2];
            for (int i = 0; i < arr.length; i++) {
                temp[i]=arr[i];
            }
            arr=temp;
        }
        //如何插入一个元素
        //即将当前位于该位置的元素以及所有后续元素右移一个位置。
        for (int i = index; i < size; i++) {
            arr[i+1]=arr[i];
        }
        arr[index]=date;
        size++;
        return true;
    }

    @Override
    public boolean set(int index, E date) {
        checkElementIndex(index);
        arr[index]=date;
        return true;
    }

    @Override
    public E remove(E date) {
        E oldDate=null;
        for (int i = 0; i < size; i++) {
            if (date == arr[i] || date.equals(arr[i])) {
                oldDate = (E) arr[i];
                for (int j = 0; j < size-1; j++) {
                    arr[j]=arr[j+1];
                }
                break;
            }
        }
        size--;
        return oldDate;
    }

    @Override
    public E remove(int index) {

        return null;
    }

    @Override
    public E getValue(int index) {
        checkElementIndex(index);
        return (E) arr[index];
    }

    private void checkElementIndex(int index) {
        if (index<0||index>=size){
            throw new RuntimeException("索引越界");
        }
    }

    @Override
    public int size() {
        return size;
    }
}
